# -*- coding: utf-8 -*-

import json
import time
from .repository import Repository

class Project(object):
    def __init__(self, client, item):
        self.client = client
        self.id = item['project_id']        
        self.name = item['name']
        self.type = item['project_type']
        self.repo_list = []
    
    def repositories(self):
        url = '/codehub/v2/projects/' + self.id + '/repositories'
        response = self.client.get_data(url)
        data = json.loads(response.text)['result']['repositories']
        for item in data:
            self.repo_list.append(Repository(self.client, item))
        return self.repo_list
    
    def find_repo_by_name(self, name):
        if self.repo_list == []:
            self.repositories()
        for repo in self.repo_list:
            if repo.name == name:
                return repo
        return None
    
    def create_repo_by_name(self, name):
        url = '/codehub/v1/repositories'
        data = {
            "name": name,
            "project_uuid": self.id,
            "import_members": 0
        }
        response = self.client.post_data(url, data)
        uuid = json.loads(response.text)['result']['repository_uuid']
        time.sleep(10)
        repo = Repository.find_by_uuid(self.client, uuid)
        self.repo_list.append(repo)
        return repo

    @staticmethod
    def create(client, project_name):
        url = '/pcedge/v1/projects'
        data = {
            "name": project_name,
            "description": "",
            "type": "scrum",
            "homepage": ""
        }
        response = client.post_data(url, data)
        uuid = json.loads(response.text)['result']['project']['project_uuid']
        return Project.find_by_uuid(client, uuid)

    @staticmethod
    def find_by_uuid(client, uuid):
        url = client.get_full_url('projectman', '/v3/project/' + uuid)
        response = client.get_data(url)
        item = json.loads(response.text)['result']
        return Project(client, item)